<?php
declare (strict_types = 1);

namespace app\middleware;

use DateTimeImmutable;
use think\Response;
use app\common\traits\Jwt;
use think\facade\Env;
/**
 * 中间件：检测Token
 */
class CheckToken
{
    use Jwt;
    public function __construct(){}
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // if(Env::get('APP_DEBUG')) {
        //     $response = $next($request);
        //     $request->uid = 0;
        //     return $response;
        // }
        $authorization_str =  $request->header('Authorization','');
        $token_str = substr($authorization_str,7);
        if(!empty($token_str)) {
            // Before
            try {
                $token = $this->parse_token($token_str);
                // 注入Token内容
                $request->token = $token;
                // 获取自定义内容uid
                $request->uid = $token->claims()->get('uid');
            } catch (\Exception $e) {
                // 返回错误
                return Response::create()->code(401)->data($e->getMessage());
            }
        } else {
            // 请求header中没有Authorization字段，或字段内容为空
            return Response::create()->code(403)->data('未登录!');
        }
        $response = $next($request);
        // After
        return $response;
    }
    /**
     * 结束调度
     *
     * @param \think\Response $response
     * @return void
     */
    public function end(\think\Response $response)
    {
        // 回调行为
    }
}
